package org.finesys.common.security.authentication.configurer;

import org.finesys.common.constants.SecurityConstants;
import org.finesys.common.security.authentication.handler.FormAuthenticationFailureHandler;
import org.finesys.common.security.authentication.handler.SsoLogoutSuccessHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;

/**
 * 基于授权码模式 统一认证登录 spring security & sas 都可以使用 所以抽取成 HttpConfigurer
 */
public class FormIdentityLoginConfigurer extends AbstractHttpConfigurer<FormIdentityLoginConfigurer, HttpSecurity> {

    @Override
    public void init(HttpSecurity httpSecurity) throws Exception {
        //登录处理
        httpSecurity.formLogin(form -> {
            form.loginPage("/token/login").permitAll();//无需授权即可访问当前页面
            form.loginProcessingUrl("/oauth2/form");//
            form.failureUrl("/login?error");//校验失败时跳转的地址，默认参数是error
            form.usernameParameter("username")// //用户名字段修改
                    .passwordParameter("password");// //密码字段修改
            form.failureHandler(new FormAuthenticationFailureHandler());//登录失败回调
        });
        //登出处理
        httpSecurity.logout(httpSecurityLogoutConfigurer -> {
            httpSecurityLogoutConfigurer.logoutUrl("/oauth2/logout").logoutSuccessHandler(new SsoLogoutSuccessHandler());//登出回调处理
            httpSecurityLogoutConfigurer
                    .deleteCookies(SecurityConstants.COOKIES)//清除cookie
                    .invalidateHttpSession(true);//清除缓存
            httpSecurityLogoutConfigurer.clearAuthentication(true);//清除权限认证信息
        });
        //跨域请求处理
        httpSecurity.csrf(AbstractHttpConfigurer::disable);
    }
}
